package com.ssy.lingxi.component.redis.config;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis序列化类
 * @author jw.chen
 * @date 2020-08-01
 */
public class SerializeUtils {
    /**
     * 序列化方法
     * @param object 缓存的对象
     * @return byte数组
     */
    public static byte[] serialize(Object object) {
    	if(object == null) {
    		return null;
    	}
        ObjectOutputStream oos;
        ByteArrayOutputStream baos;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 反序列化
     * @param bytes 缓存中的byte数组
     * @return 对象
     */
    public static Object deserialize(byte[] bytes) {
    	if(bytes == null) {
    		return null;
    	}
        ByteArrayInputStream bais;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 反序列化Map对象
     * @param bytes 缓存中的Map对象
     * @return Map对象
     */
    public static Map<byte[], Object> deserializeMap(Map<byte[], byte[]> bytes) {
    	if(bytes == null) {
    		return null;
    	}
    	Map<byte[], Object> map = new HashMap<>();
    	ByteArrayInputStream bais;
    	try {
    		for (Map.Entry<byte[], byte[]> entry : bytes.entrySet()) {
    			byte[] key = entry.getKey();
				byte[] value = entry.getValue();
	    		bais = new ByteArrayInputStream(value);
	    		ObjectInputStream ois = new ObjectInputStream(bais);
    			map.put(key, ois.readObject());
    		}
    		return map;
    	} catch (Exception e) {
    		throw new RuntimeException(e.getMessage(), e);
    	}
    }
}
